<template>
  <div class="his_container">
    <div class="header">
      <!-- <h1><img src="~@/assets/images/logo_apply.png" alt="影像检查临床分时段预约系统"></h1>
      <h5><img src="~@/assets/images/topbg.png"></h5> -->
      <span>您好！<i id="operateUser"></i>{{hospitalName}} {{userName}}，欢迎进入影像检查HIS申请系统</span>
    </div>
    <div
      class="ky-container"
      v-loading="loading"
    >
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="8" :lg="8">
          <el-card class="his_table">
            <div slot="header" class="clearfix">
              <span style="font-size: 16px; font-weight: bold;line-height: 28px;">申请单列表</span>
              <div style="float: right;">
                <!-- <el-date-picker
                  v-model="hisFormDate"
                  type="daterange"
                  align="right"
                  size="small"
                  unlink-panels
                  :clearable="false"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
                </el-date-picker> -->
                <el-button type="primary" size="mini" @click="getHisExamList" icon="el-icon-search">搜索</el-button>
              </div>
            </div>
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              class="ky-table"
            >
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button size="small" type="primary" @click="appointment(scope.row)">预约</el-button>
                </template>
              </el-table-column>
              <!-- <el-table-column type="index" label="序号" width="55"></el-table-column> -->
              <el-table-column prop="patName" label="姓名"></el-table-column>
              <el-table-column prop="examClass" label="检查设备"></el-table-column>
              <el-table-column prop="checkpart" label="检查部位" min-width="140"></el-table-column>
              <el-table-column prop="checkbody" label="检查项目"></el-table-column>
              <el-table-column prop="patientSource" label="病人类型" :formatter="getSource"></el-table-column>
              <el-table-column prop="applyDateTime" label="申请时间" min-width="180"></el-table-column>
              <el-table-column prop="patientId" label="PID" min-width="180"></el-table-column>
              <el-table-column prop="idCard" label="病人身份证" min-width="180"></el-table-column>
              <el-table-column prop="patientPhone" label="病人手机号" min-width="180"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <!-- <el-col :xs="24" :sm="24" :md="24" :lg="24"> -->
        <el-col :xs="24" :sm="24" :md="16" :lg="16">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="font-size: 16px; font-weight: bold;line-height: 28px;">申请单信息</span>
              <div style="float: right;">
                <el-button v-if="check_query_hr_show" type="" size="mini" @click="onQuery">区域检查<span>(<b class="fc_red">{{QueryListNum}}</b>)</span></el-button>
                <el-button type="primary" size="mini" @click="onSend">提交申请</el-button>
              </div>
            </div>
            <div>
              <!-- <el-row :gutter="10">
                <el-col :xs="24" :sm="24" :md="18" :lg="18"> -->
              <el-form
                ref="applyForm"
                :model="formdata"
                label-width="80px"
                :rules="rules"
              >
                <el-row :gutter="5">
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="病人类型" prop="patientSource">
                      <el-select v-model="formdata.patientSource" clearable style="width: 100%;" @change="chagnePatientSource">
                        <el-option
                          v-for="item in patientSourceOptions"
                          :key="item.value"
                          :value="item.value"
                          :label="item.label"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="姓名" prop="patientName">
                      <el-input v-model="formdata.patientName" placeholder="姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="formdata.gender">
                        <el-radio :label="1" style="margin-right: 4px;">男</el-radio>
                        <el-radio :label="2" style="margin-right: 4px;">女</el-radio>
                        <el-radio :label="9" style="margin-right: 4px;">其他</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="年龄" prop="patientAge">
                      <el-input v-model="formdata.patientAge" placeholder="年龄">
                        <el-select
                          v-model="formdata.patientAgeUnit"
                          slot="append"
                          @change="ageChange"
                          style="width: 60px;"
                        >
                          <el-option
                            label="岁"
                            value="Y"
                          ></el-option>
                          <el-option
                            label="月"
                            value="M"
                          ></el-option>
                          <el-option
                            label="天"
                            value="D"
                          ></el-option>
                        </el-select>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-if="formdata.patientSource === 1">
                    <el-form-item label="门诊号" prop="clinicCode">
                      <el-input v-model="formdata.clinicCode" placeholder="门诊号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-if="formdata.patientSource === 2">
                    <el-form-item label="住院号" prop="hospizationCode">
                      <el-input v-model="formdata.hospizationCode" placeholder="住院号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="身份证" prop="idCard">
                      <el-input v-model="formdata.idCard" placeholder="身份证" @change="idCardChange"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="出生日期" prop="birthDate">
                      <el-date-picker
                        v-model="formdata.birthDate"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%;"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="病区" prop="wardName">
                      <el-input v-model="formdata.wardName" placeholder="病区"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="床位号" prop="bedNo">
                      <el-input v-model="formdata.bedNo" placeholder="床位号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="联系地址" prop="address">
                      <el-input v-model="formdata.address" placeholder="联系地址"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="联系电话" prop="patientPhone">
                      <el-input v-model="formdata.patientPhone" placeholder="联系电话"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="患者ID" prop="patientId">
                      <el-input v-model="formdata.patientId" placeholder="患者ID"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="病史" prop="diseasesHistory">
                      <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 10 }"
                        v-model="formdata.diseasesHistory"
                        placeholder="病史"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="临床诊断" prop="clinicdiagnosis">
                      <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 10 }"
                        v-model="formdata.clinicdiagnosis"
                        placeholder="临床诊断"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="检查部门" prop="examClass">
                      <el-select v-model="formdata.examClass" clearable filterable @change="examClassChange" style="width:100%;">
                        <el-option
                          v-for="(item, index) in checkTypeData"
                          :key="index"
                          :value="item"
                          :label="item"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="16" :xl="18">
                    <el-form-item label="检查项目" prop="examItemsData">
                      <el-select v-model="formdata.examItemsData" multiple filterable clearable>
                        <el-option
                          v-for="item in examItemsOptions"
                          :key="item.id"
                          :value="item.id"
                          :label="item.smallpart"
                        ></el-option>
                      </el-select>
                      <el-checkbox v-model="selectedPage" @change="selectedPageChange">全部</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="申请医生" prop="applyDoctor">
                      <el-input v-model="formdata.applyDoctor" placeholder="申请医生"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="申请科室" prop="applyDepartment">
                      <el-input v-model="formdata.applyDepartment" placeholder="申请科室"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="申请时间" prop="applyDateTime">
                      <el-date-picker
                        v-model="formdata.applyDateTime"
                        type="datetime"
                        placeholder="选择日期时间"
                        style="width: 100%;"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="执行科室" prop="examExecuteDepartment">
                      <el-select v-model="formdata.examExecuteDepartment" clearable style="width: 100%;">
                        <el-option
                          v-for="item in depOptions"
                          :key="item"
                          :value="item"
                          :label="item"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="申请单号" prop="applyCode">
                      <el-input v-model="formdata.applyCode" placeholder="申请单号"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                    <el-form-item label="申请状态" prop="examStatus">
                      <el-select v-model="formdata.examStatus" clearable style="width: 100%;">
                        <el-option
                          v-for="item in examStatusOptions"
                          :key="item.value"
                          :value="item.value"
                          :label="item.label"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                </el-row>
              </el-form>
              <!-- </el-col> -->
              <!-- </el-row> -->
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 预约展示 -->
      <el-dialog
        title="智能预约号源"
        :visible.sync="dialogVisible"
        :destroy-on-close="true"
        width="80%">
        <div class="appo_dlg">
          <el-table
            :data="tableDataAppo"
            border
            style="width: 100%">
            <el-table-column type="index" label="序号" width="55"></el-table-column>
            <el-table-column prop="patName" label="姓名"></el-table-column>
            <el-table-column prop="examClass" label="检查设备"></el-table-column>
            <el-table-column prop="checkpart" label="检查部位" min-width="200"></el-table-column>
            <el-table-column prop="checkbody" label="检查项目"></el-table-column>
            <el-table-column prop="appoDate" label="预约日期" min-width="150">
              <template slot-scope="scope">
                <span>{{scope.row.appoDate}} {{scope.row.appoTime}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="room" label="预约机房" min-width="150"></el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="appointmentSend(scope.row, scope.$index)">预约</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="sendAppo">预约</el-button>
          <el-button size="small" type="success" @click="goAppoApp">自定义预约</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import enc from '@/utils/aes'
import {
  postScheduleTrade,
  getHisDepTree,
  getDepList,
  postHisRegisterpartGetadvancepages,
  postHisExam,
  getModalityTypeList,
  getSysHospitalGetModelByCode
} from '@/api/api'
import {
  dateFormatter,
  isIdCard,
  sexById,
  birthdayById,
  birthdayByAge,
  getNewUUID
} from '@/utils/validate'
import { Options } from '@/utils/constant'

// // 检查互认测试
// const hurenCheck = {
//   patientName: '陈金炎',
//   bigpart: '胸部平扫'
// }
const _publicKey = '04EFDFAC361CA6B46D50EF7A655D23343E59AC0AB30FC0AE00876CF9E1324A91C35A23E8AF447596ACD85AEDA15FF74C9EA2B3E5D0C2810778D808B667AE58F1D8'
export default {
  data() {
    return {
      loading: false,
      isEncrypt: true,
      pubcliKey: null,
      userName: this.$store.state.user.userName,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      'formdata': {
        patientId: '', // 病人id
        'masterPatientIndexId': '', // 主索引
        'idCard': '', // 身份证
        'ssnCardNo': '', // 社保卡
        patientName: '', // 姓名
        birthDate: '', // 出生日期
        gender: 1, // 性别 值域：0-未知的性别；1-男性；2-女；9-未说明的性别
        'address': '', // 联系地址
        'patientPhone': '', // 联系电话
        organizationCode: this.$store.state.user.hospitalCode, // 档案所属机构

        'visitNo': '', // 就诊号
        'visitNumber': 0,
        patientAge: '', // 年龄 21Y/8M/9D/10H
        patientAgeUnit: 'Y', // 21Y/8M/9D/10H
        patientSource: 1, // 值域：1-门诊；2-住院；3-体检；5-急诊
        'medicalCardNo': '', // 就诊卡号
        'medicalRecordNo': '', // 病历号
        'clinicCode': '', // 门诊号
        'hospizationCode': '', // 住院号
        visitDateTime: dateFormatter(new Date()), // 就诊时间
        'visitDeparmentCode': '', // 就诊科室代码
        'visitDeparment': '', // 就诊科室
        'attendDoctorCode': '', // 接诊医生代码
        'attendDoctor': '', // 就诊医生
        'diagnosis': '', // 诊断
        'icD10': '', // icd10
        'bedNo': '', // 床号
        'wardName': '', // 病区
        'wardNo': '', // 病区代码
        'roomNo': '', // 病房号

        applyCode: '', // 申请单号
        'medicalAdviceNo': '', // 医嘱号
        examClass: '', // 申请单类型  类型代码:CT/MRI/US等  检查部门
        'examClassCode': '', // 申请单类型代码
        'clinicdiagnosis': '', // 临床诊断
        'chiefComplaint': '', // 主诉
        'diseasesHistory': '', // 电子病史
        'physicalSign': '', // 体征
        'allergicHistory': '', // 过敏史
        'drugResistanceHistory': '', // 耐药史
        'examPurpose': '', // 检查目的
        'isEmergency': true,
        applyDepartment: this.$store.state.user.deptName, // 申请单科室
        applyDepartmentCode: this.$store.state.user.deptCode, // 申请科室代码
        applyDoctor: this.$store.state.user.userName, // 申请医生
        applyDoctorCode: this.$store.state.user.userCode, // 申请医生代码
        examText: '', // 申请单项目
        cost: 0, // 总价
        examExecuteDepartmentCode: '', // 执行科室代码
        examExecuteDepartment: '', // 执行科室
        'remarkInfo': '', // 备注
        'effectiveFlag': true,
        applyDateTime: dateFormatter(new Date()), // 申请时间
        examStatus: 5, // 值域：0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        feeStatus: true, // 是否收费
        'invoiceNo': '',
        examItemsData: [], // 胸部平扫
        examItems: [] // 检查项目
      },
      rules: {
        patientId: [{ required: true, message: '请输入患者ID', trigger: 'blur' }],
        patientName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        patientAge: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        birthDate: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
        idCard: [{ required: !!window.g.CHECK_QUERY_HR_SHOW, message: '请输入身份证', trigger: 'blur' }],
        patientSource: [{ required: true, message: '请选择病人类型', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        visitDateTime: [{ required: true, message: '请选择就诊时间', trigger: 'blur' }],
        applyDepartment: [{ required: true, message: '请选择申请科室', trigger: 'change' }],
        applyDoctor: [{ required: true, message: '请选择申请医生', trigger: 'change' }],
        applyCode: [{ required: true, message: '请输入申请单号', trigger: 'blur' }],
        examClass: [{ required: true, message: '请选择检查部门', trigger: 'change' }],
        examItemsData: [{ required: true, message: '请选择检查项目', trigger: 'change' }]
      },
      patientSourceOptions: Options.patientTypeItemOptions,
      examStatusOptions: [
        // 0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        { value: 0, label: '已登记' },
        { value: 1, label: '已检查' },
        { value: 2, label: '已报告' },
        { value: 3, label: '已审核' },
        { value: 4, label: '已作废' },
        { value: 5, label: '原始' }
      ], // 项目值域
      selectedPage: false, // 全部
      pageSize: 100, // 项目属性数据
      totalCount: 0, // 项目属性数据总条数
      examItemsOptions: [], // 项目选项
      examPartsOptions: [], // 部位选项
      depOptions: [], // 部门选项
      checkTypeData: [],
      filterData: [],
      defaultProps: {
        children: 'childrens',
        label: 'text'
      },
      hisFormDate: [dateFormatter(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), dateFormatter(new Date().getTime())],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      tableData: [],
      currApply: null,

      // 预约号源展示
      dialogVisible: false,
      tableDataAppo: [],

      // 自定义预约
      pathOptions: [
        {
          label: '移动端',
          // value: 'http://192.168.0.91:9050/medicalTechnologyAppointment'
          value: 'http://192.168.0.91:9061/consultationLogin'
        }, {
          label: 'PC端',
          value: 'http://192.168.0.91:9062/index.html'
        }, {
          label: '其它',
          value: '其它'
        }
      ],
      formdataOther: {
        hospCode: this.$store.state.user.hospitalCode,
        hospName: '',
        url: '',
        // path: 'http://192.168.0.91:9050/medicalTechnologyAppointment',
        path: 'http://192.168.0.91:9062/index.html',
        patId: '',
        idCard: '', // 患者身份证
        tel: '', // 患者手机号
        operateCode: '1234',
        examClass: '小腿',
        operateUser: this.$store.state.user.userName,
        api: 'http://192.168.0.38:9217',
        other: '&ps=0&pw=6&edm=wo'
      },
      // 区域调阅检查数量
      check_query_hr_show: window.g.CHECK_QUERY_HR_SHOW, // 区域查询，互认是否显示执行
      QueryListNum: 0,
      check_hr_query_url: window.g.CHECK_HR_QUERY_URL, // || 'http://192.168.0.91:9117',
      appoint_url: window.g.APPOINT_URL, // || 'http://192.168.0.91:9062/index.html',
      api_root_check: window.g.API_ROOT_CHECK // || 'http://192.168.0.156:9222'
    }
  },
  async created() {
    await Promise.all([this.$getHospitalList(), this.gethospitalInfo(this.hospitalCode)])
    this.$nextTick(() => {
      this.hospChange()
    })
    this.resetForm()
    // this.getHisTree()
    this.getModalityTypeList()
    this.getHISCheckpart()
    this.getDepListData()

    // 获取HIS申请单列表数据
    this.getHisExamList()
    // 区域检查记录
    // if (this.api_root_check && this.check_query_hr_show && this.formdata.patientName) {
    //   this.postRisexaminfoCheck().then((res) => {
    //     this.QueryListNum = res.content
    //     this.check_hr_resUrl = res.message
    //   })
    // }
  },
  methods: {
    gethospitalInfo(hospitalCode) {
      return new Promise(async resolve => {
        await getSysHospitalGetModelByCode({ hospitalCode }).then(res => {
          // this.pubcliKey = res.content.guomiKey
          if (!window.g.API_ROOT_SCHEDULE) {
            window.g.API_ROOT_SCHEDULE = res.content.hiswebservice
          }
        })
        resolve()
      })
    },
    async onQuery() {
      if (this.QueryListNum > 0) {
        if (this.check_hr_resUrl) {
          window.open(this.check_hr_resUrl, '_blank')
        } else if (this.check_hr_query_url) {
          const data = await this.getSignatureParams(2)
          const params = this.getParamsString(data)
          const url = this.check_hr_query_url + '/hisLogin?' + params
          window.open(url, '_blank')
        }
      } else if (this.api_root_check && this.check_query_hr_show) {
        if (!this.formdata.patientName) {
          this.$message.info('患者姓名不能为空')
          return
        }
        if (!this.formdata.idCard) {
          this.$message.info('患者身份证不能为空')
          return
        }
        this.postRisexaminfoCheck().then(res => {
          this.QueryListNum = res.content
          this.check_hr_resUrl = res.message
          if (!this.QueryListNum) {
            this.$message.info('暂无区域检查记录！')
          } else if (this.check_hr_resUrl) {
            window.open(this.check_hr_resUrl, '_blank')
          }
        })
      }
    },
    onSend() {
      // console.log('this.$route.query.debug', typeof this.$route.query.debug)
      if (this.$route.query.debug == 'true') {
        // console.log(2)
        if (this.check_query_hr_show && this.check_hr_query_url) {
          this.postMutualCheck().then((resUrl) => {
          // 互认弹框
            this.$confirm('当前患者存在匹配的互认检查！', '互认提示', {
              confirmButtonText: '去互认',
              cancelButtonText: '继续开单',
              type: 'warning',
              distinguishCancelAndClose: true
            }).then(async () => {
              if (resUrl) {
                console.log('resUrl', resUrl)
                window.open(resUrl, '_blank')
              } else {
                const data = await this.getSignatureParams(3)
                const params = this.getParamsString(data)
                const url = this.check_hr_query_url + '/hisLogin?' + params
                window.open(url, '_blank')
              }
            }).catch((action) => {
            // console.log(action)
              if (action === 'cancel') {
              // 继续开单
                this.sendApply()
              }
            })
          }).catch((error) => {
            if (error) {
            // 继续开单
              this.sendApply()
            }
          })
        } else {
          this.sendApply()
        }
      } else {
        this.sendApply()
      }
    },
    // 申请提交
    async sendApply() {
      console.log(this.formdata)
      const valid = await this.$refs.applyForm.validate()
      if (!valid) return
      const userInfo = this.$store.state.user.userInfo
      console.log('userInfo', userInfo)
      const applyData = this.getApplyData()
      const params = {
        data: applyData,
        'hospitalCode': this.hospitalCode,
        'timestamp': 0,
        'tradeCode': 0, //  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
        'signature': '',
        'operator': userInfo.userName,
        'operatorCode': userInfo.userCode,
        'operatorDepartmnet': userInfo.deptName,
        'operatorDepartmnetCode': userInfo.deptCode
      }
      console.log('params', params)
      // if (params) return
      this.loading = true
      postScheduleTrade(params).then(res => {
        this.loading = false
        console.log('postScheduleTrade', res)
        if (res.code === 1) {
          this.$message.success(res.message || '申请单提交成功！')
          this.getHisExamList()
          this.resetForm()
        }
      })
    },
    getApplyData() {
      const fd = this.formdata
      const params = {
        patient: {
          patientId: fd.patientId, // 病人id
          masterPatientIndexId: fd.masterPatientIndexId, // 主索引
          idCard: fd.idCard, // 身份证
          ssnCardNo: fd.ssnCardNo, // 社保卡
          patientName: fd.patientName, // 姓名
          birthDate: fd.birthDate, // 出生日期
          gender: fd.gender, // 性别 值域：0-未知的性别；1-男性；2-女；9-未说明的性别
          address: fd.address, // 联系地址
          patientPhone: fd.patientPhone, // 联系电话
          organizationCode: fd.organizationCode// 档案所属机构
        },
        visit: {
          visitNo: fd.visitNo, // 就诊号
          visitNumber: fd.visitNumber,
          patientAge: fd.patientAge + fd.patientAgeUnit, // 年龄
          patientSource: fd.patientSource, // 值域：1-门诊；2-住院；3-体检；5-急诊
          medicalCardNo: fd.medicalCardNo, // 就诊卡号
          medicalRecordNo: fd.medicalRecordNo, // 病历号
          clinicCode: fd.clinicCode, // 门诊号
          hospizationCode: fd.hospizationCode, // 住院号
          visitDateTime: fd.visitDateTime, // 就诊时间
          visitDeparmentCode: fd.visitDeparmentCode, // 就诊科室代码
          visitDeparment: fd.visitDeparment, // 就诊科室
          attendDoctorCode: fd.attendDoctorCode, // 接诊医生代码
          attendDoctor: fd.attendDoctor, // 就诊医生
          diagnosis: fd.diagnosis, // 诊断
          icD10: fd.icD10, // icd10
          bedNo: fd.bedNo, // 床号
          wardName: fd.wardName, // 病区
          wardNo: fd.wardNo, // 病区代码
          roomNo: fd.roomNo // 病房号
        },
        examinations: []
      }

      const examItems = this.getSelectedCheckPartData()
      const examinationsObj = {
        examItems,
        applyCode: fd.applyCode, // 申请单号
        medicalAdviceNo: fd.medicalAdviceNo, // 医嘱号
        examClass: fd.examClass, // 申请单类型  类型代码:CT/MRI/US等  检查部门
        examClassCode: fd.examClassCode, // 申请单类型代码
        clinicdiagnosis: fd.clinicdiagnosis, // 临床诊断
        chiefComplaint: fd.chiefComplaint, // 主诉
        diseasesHistory: fd.diseasesHistory, // 电子病史
        physicalSign: fd.physicalSign, // 体征
        allergicHistory: fd.allergicHistory, // 过敏史
        drugResistanceHistory: fd.drugResistanceHistory, // 耐药史
        examPurpose: fd.examPurpose, // 检查目的
        isEmergency: fd.isEmergency,
        applyDepartment: fd.applyDepartment, // 申请单科室
        applyDepartmentCode: fd.applyDepartmentCode, // 申请科室代码
        applyDoctor: fd.applyDoctor, // 申请医生
        applyDoctorCode: fd.applyDoctorCode, // 申请医生代码
        examText: fd.examText, // 申请单项目
        cost: fd.cost, // 总价
        isApply: 1,
        examExecuteDepartmentCode: fd.examExecuteDepartmentCode, // 执行科室代码
        examExecuteDepartment: fd.examExecuteDepartment, // 执行科室
        remarkInfo: fd.remarkInfo, // 备注
        effectiveFlag: fd.effectiveFlag,
        applyDateTime: dateFormatter(new Date()), // 申请时间
        examStatus: fd.examStatus, // 值域：0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        feeStatus: fd.feeStatus, // 是否收费
        invoiceNo: fd.invoiceNo
      }
      params.examinations[0] = examinationsObj

      return params
    },
    getSelectedCheckPartData() {
      // 获取检查部位（level2）
      let eItems = this.formdata.examItemsData
      const examItems = []
      for (let i = 0; i < eItems.length; i++) {
        const bpObj = this.examItemsOptions.find(item => item.id === eItems[i])
        if (bpObj) {
          const examItem = {
            'examItemNo': '', // 医技序号
            'examItemCode': bpObj.smallpart, // 项目代码
            'examItemName': bpObj.smallpart,
            'examMethod': '', // 检查方法
            'price': 0,
            'amount': 0,
            'feeStatus': true,
            'examParts': []
          }
          const examPart = {
            'examPartCode': bpObj.bigpart, // 部位代码
            'examPart': bpObj.bigpart, // 部位名称
            'examPartDesc': '' // 检查方法说明
          }
          const eObjIndex = examItems.findIndex(item => item.examItemName === bpObj.smallpart)
          if (eObjIndex >= 0) {
            examItems[eObjIndex].examParts.push(examPart)
          } else {
            examItem.examParts.push(examPart)
            examItems.push(examItem)
          }
        }
      }
      console.log('examItems', examItems)
      return examItems
    },

    getHisTree() {
      const params = {
        HospitalCode: this.hospitalCode,
        dep: this.$store.state.user.deptName
      }
      getHisDepTree(params).then(res => {
        if (res && res.code === 10000) {
          let depNodes = res.content.childrens
          for (let i = 0; i < depNodes.length; i++) {
            let tempLevel1 = { text: depNodes[i].text, level: 1, childrens: [], id: depNodes[i].text }
            // 如果存在部位
            if (depNodes[i].childrens && depNodes[i].childrens.length !== 0) {
              for (let j = 0; j < depNodes[i].childrens.length; j++) {
                let level1Children = depNodes[i].childrens
                // 加上level防止同名
                let tempLevel2 = { text: level1Children[j].text, level: 2, childrens: [], id: level1Children[j].text, parentId: tempLevel1.id }
                if (level1Children[j].childrens && level1Children[j].childrens.length !== 0) {
                  tempLevel2.childrens = level1Children[j].childrens.map(item => {
                    return { text: item.text, level: 3, childrens: [], id: tempLevel2.id + item.text, parentId: tempLevel2.id, grandId: tempLevel2.parentId }
                  })
                }
                tempLevel1.childrens.push(tempLevel2)
              }
            }
            this.checkTypeData.push(tempLevel1)
          }
        }
      })
    },
    getModalityTypeList() {
      const params = {
        HospitalCode: this.hospitalCode
        // dep: this.$store.state.user.deptName
      }
      getModalityTypeList(params).then(res => {
        if (res && res.code === 10000) {
          let depTypes = res.content.list
          // console.log('depTypes', depTypes)
          this.checkTypeData = depTypes
        }
      })
    },
    // 获取检查项目列表
    getHISCheckpart() {
      const params = {
        hospitalCode: this.hospitalCode,
        dep: '',
        modality: this.formdata.examClass,
        checkRoom: '',
        partType: -1, // 省对照部位
        filterType: -1, // 过滤
        workCountType: -1, // 系数类型
        pageSize: this.selectedPage ? this.totalCount : this.pageSize,
        pageNumber: 1
      }
      postHisRegisterpartGetadvancepages(params).then(res => {
        if (res) {
          this.examItemsOptions = res.content.list
          this.totalCount = res.content.totalCount
        }
      })
    },
    selectedPageChange() {
      this.getHISCheckpart()
    },
    // 获取HIS检查列表
    getHisExamList() {
      const userInfo = this.$store.state.user.userInfo
      const params = {
        queryWay: 0, // 查询方式
        requestStartDateTime: this.hisFormDate ? dateFormatter(this.hisFormDate[0]) : '', // 申请单开始时间
        requestEndDateTime: this.hisFormDate ? dateFormatter(this.hisFormDate[1]) : '', // 申请单结束时间
        organizationCode: this.hospitalCode, // 申请医院代码
        operateCode: userInfo.userCode, // 操作人编号 可传工号
        operateUser: userInfo.userName, // 操作人姓名
        patientSource: this.formdata.patientSource // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
      }
      this.loading = true
      postHisExam(params).then(res => {
        this.loading = false
        if (res) {
          this.getHisTableList(res.content.list)
        }
      })
    },
    getHisTableList(data) {
      const _data = []
      data.forEach(item => {
        const _obj = {
          patientId: item.patient.patientId,
          patientPhone: item.patient.patientPhone,
          organizationCode: item.patient.organizationCode, // 申请医院代码
          patName: item.patient.patientName,
          idCard: item.patient.idCard,
          patAge: item.visit.patientAge,
          gender: item.visit.gender,
          birthDate: item.visit.birthDate,
          patientSource: item.visit.patientSource, // 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
          applyDateTime: item.examinations[0].applyDateTime,
          applyCode: item.examinations[0].applyCode,
          applyDoctor: item.examinations[0].applyDoctor,
          applyDepartment: item.examinations[0].applyDepartment,
          examExecuteDepartmentCode: item.examinations[0].examExecuteDepartmentCode, // 执行科室代码
          examExecuteDepartment: item.examinations[0].examExecuteDepartment, // 执行科室
          examClass: item.examinations[0].examClass, // 'MR',
          examItemCode: item.examinations[0].examItems[0].examItemCode, // '脊柱,颈部',
          examItemName: item.examinations[0].examItems[0].examItemName, // '脊柱,颈部',
          checkbody: item.examinations[0].examItems[0].examParts[0].examPart, // '脊柱,颈部',
          checkpart: item.examinations[0].examItems[0].examItemName // '1.5T磁共振腰椎平扫,1.5T磁共振颈部平扫'
        }
        _data.push(_obj)
      })
      const ddSort = (a, b) => {
        return new Date(b.applyDateTime).getTime() - new Date(a.applyDateTime).getTime()
      }
      this.tableData = _data.sort(ddSort)
    },
    // 检查部门改变
    examClassChange() {
      if (this.formdata.examClass) {
        this.getHISCheckpart()
        this.formdata.examItemsData = []
      } else {
        this.examItemsOptions = []
      }
    },
    // 获取科室信息
    getDepListData() {
      const params = {
        HospitalCode: this.hospitalCode
      }
      getDepList(params).then(res => {
        this.depOptions = res.content.list
      })
    },
    // 互认
    postMutualCheck() {
      return new Promise(async (resolve, reject) => {
        const params = await this.getSignatureParams(3)
        await axios({
          method: 'post',
          baseURL: this.api_root_check,
          url: '/api/mutual/check',
          timeout: 1000000,
          headers: {
            ...params
          }
        }).then(resq => {
          if (resq.status === 200) {
            const res = resq.data
            console.log(res)
            if (res.code === 1 && res.content) {
              // 互认弹框
              resolve(res.message)
            } else if (res.code === 401) {
              this.$message.error(res.message || '返回错误：' + res.code)
              reject(false)
            } else {
              reject(true)
            }
          }
        }).catch(error => {
          console.error('postMutualCheck >>> ', error)
          reject(error)
        })
      })
    },
    // 区域
    postRisexaminfoCheck() {
      return new Promise(async (resolve, reject) => {
        const params = await this.getSignatureParams(2)
        // 陈金炎
        await axios({
          method: 'post',
          baseURL: this.api_root_check,
          url: '/api/risexaminfo/check',
          timeout: 1000000,
          headers: {
            ...params
            // ...signatureData2
          }
        }).then(resq => {
          if (resq.status === 200) {
            const res = resq.data
            console.log(res)
            if (res.code === 1 && (res.content || res.content === 0)) {
              resolve(res)
            } else {
              this.$message.error(res.message)
              reject(true)
            }
          }
        }).catch(error => {
          console.error('postRisexaminfoCheck >>> ', error)
          reject()
        })
      })
    },
    // 区域查询请求数据加密
    getSignatureParams(ExamFlg) {
      // ExamFlg 检查标识（0：院内+区域，1:院内查询，2：区域查询,3:互认查询）
      return new Promise(resolve => {
        const _time = Math.floor(new Date().getTime() / 1000)
        const userInfo = this.$store.state.user.userInfo
        const MutualCode = ExamFlg === 3 ? this.getMutualCode() : ''
        const pkey = window.g.CHECK_HR_QUERY_PUBLICKEY ? window.g.CHECK_HR_QUERY_PUBLICKEY : this.pubcliKey ? this.pubcliKey : _publicKey
        const params = {
          'ExamFlg': ExamFlg,
          'HospitalCode': this.hospitalCode,
          'HospitalName': this.hospitalName,
          'DoctorCode': userInfo.userCode,
          'DoctorName': userInfo.userName,
          'DoctorIdCard': userInfo.cardId,
          'MutualCode': MutualCode,
          'PatientId': this.formdata.patientId,
          'PatientName': this.formdata.patientName,
          'PatientIdCard': this.formdata.idCard,
          'PatientTelephone': this.formdata.patientPhone
        }
        console.log('getSignatureParams params', params)
        console.log('getSignatureParams pkey', pkey)
        const SM2EncryptData = '04' + enc.SM2Encrypt(JSON.stringify(params), pkey).toUpperCase()
        const sign = enc.sha1Encrypt(this.hospitalCode + SM2EncryptData + _time)
        const data = {
          Code: this.hospitalCode,
          Data: SM2EncryptData,
          Timestamp: _time,
          Signature: sign.toUpperCase()
        }
        console.log('getSignatureParams data', data)
        resolve(data)
      })
    },
    getMutualCode() {
      let eItems = this.formdata.examItemsData
      const examItems = []
      for (let i = 0; i < eItems.length; i++) {
        const bpObj = this.examItemsOptions.find(item => item.id === eItems[i])
        console.log('bpObj', bpObj)
        if (bpObj) {
          examItems.push(bpObj.itemName)
        }
      }
      return examItems.join(',')
    },

    // 预约
    appointment(row) {
      console.log(row)
      if (!this.appoint_url) {
        this.$message.info('未配置预约地址！')
        return
      }
      const userInfo = this.$store.state.user.userInfo
      const _url = `${this.appoint_url}?hospitalCode=${this.hospitalCode}&hospitalName=${this.hospitalName}&patientId=${row.patientId}&operateUser=${userInfo.userName}&operateCode=${userInfo.userCode}&examClass=${row.examClass}&idCard=${row.idCard}&tel=&ps=${row.patientSource}&pw=0&edm=${row.examExecuteDepartment}`
      window.open(_url, '_blank')
    },
    // 确认预约，联合预约
    sendAppo() {
      this.$message.success('预约成功！')
      this.dialogVisible = false
    },
    // 单个预约
    appointmentSend(row, index) {
      this.$message.success('预约成功！')
      this.tableDataAppo.splice(index, 1)
      if (this.tableDataAppo.length === 0) {
        this.dialogVisible = false
      }
    },

    goAppoApp() {
      this.dialogVisible = false
      this.openUrl(this.currApply.id)
    },

    openUrl(patientId) {
      const urlPath = this.formdataOther.path === '其它' ? this.formdataOther.url : this.formdataOther.path
      const _url = `${urlPath}?hospitalCode=${this.formdataOther.hospCode}&hospitalName=${this.formdataOther.hospName}&patientId=${patientId}&operateUser=${this.formdataOther.operateUser}&operateCode=${this.formdataOther.operateCode}&examClass=${this.formdataOther.examClass}&idCard=${this.formdataOther.idCard}&tel=${this.formdataOther.tel}${this.formdataOther.other}`
      console.log(_url)
      const newWin = window.open(_url, '_blank')
      newWin.focus()
    },
    hospChange() {
      if (this.formdataOther.hospCode) {
        const hosp = this.mx_hospitalList.find(item => item.code === this.formdataOther.hospCode)
        if (hosp) {
          this.formdataOther.hospName = hosp.name
        }
      } else {
        this.formdataOther.hospName = ''
      }
    },

    // 根据输入身份证号，自动填写 性别、生日、年龄
    idCardChange() {
      let id = this.formdata.idCard
      if (id && isIdCard(id)) {
        this.formdata.gender = sexById(id)
        this.formdata.birthDate = birthdayById(id)
        this.setAgeValApply(this.formdata.birthDate)
      }
    },
    getMonthDay(year, month) {
      let days = new Date(year, month + 1, 0).getDate()
      return days
    },
    // 根据出生日期计算年龄
    getAgeApply(strAge) {
      var birArr = strAge.split('-')
      var birYear = birArr[0]
      var birMonth = birArr[1] * 1
      var birDay = birArr[2]

      var d = new Date()
      var nowYear = d.getFullYear()
      var nowMonth = d.getMonth() + 1 // 记得加1
      var nowDay = d.getDate()
      var returnAge; var errFlag = false; var errMsg = ''

      if (birArr == null) {
        return {
          errFlag: true,
          errMsg: '',
          val: ''
        }
      }
      var dBir = new Date(birYear, birMonth - 1, birDay)
      if (dBir.getFullYear() == birYear && (dBir.getMonth() + 1) == birMonth && dBir.getDate() == birDay) {
        if (nowYear == birYear) {
          // 同年
          // returnAge = 0; //同年
          var MonthDiff = nowMonth - birMonth // 计算月
          if (MonthDiff >= 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#D'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else if (nowMonth == birMonth + 1) {
              var preMonthDays = this.getMonthDay(birYear, birMonth)
              let dayDiff = nowDay + preMonthDays - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#D'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else {
              returnAge = MonthDiff + 1 + '#M'
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge
          }
        } else {
          // 不同年
          var ageDiff = nowYear - birYear // 计算年
          if (ageDiff > 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff < 0) {
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#Y'
                } else {
                  returnAge = 11 + '#M'
                }
              } else {
                returnAge = ageDiff + '#Y'
              }
            } else {
              var monthDiff = nowMonth - birMonth // 计算月
              if (monthDiff < 0) {
                // returnAge = ageDiff - 1;
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#Y'
                } else {
                  returnAge = Math.abs(nowMonth - birMonth + 12) + '#M'
                }
              } else {
                returnAge = ageDiff + '#Y'
              }
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'// 返回-1 表示出生日期输入错误 晚于今天
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge + '#Y'
          }
        }
      } else {
        return {
          errFlag: true,
          errMsg: '输入的日期格式错误！',
          val: ''
        }
      }
    },
    setAgeValApply(strAge) {
      var ageObj = this.getAgeApply(strAge)
      if (!ageObj.errFlag) {
        var ageArr = ageObj.val.split('#')
        this.formdata.patientAgeUnit = ageArr[1]
        this.formdata.patientAge = ageArr[0]
      } else if (ageObj.errMsg != '') {
        this.$alert(ageObj.errMsg, '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            this.formdata.birthDate = ''
          }
        })
        return false
      }
    },
    // 监听年龄变化，计算生日
    ageChange() {
      const bday = birthdayByAge(this.formdata.patientAge, this.formdata.patientAgeUnit)
      this.formdata.birthDate = bday
    },

    chagnePatientSource() {
      this.formdata.clinicCode = ''
      this.formdata.hospizationCode = ''
    },
    resetForm() {
      this.formdata.patientId = Math.random().toString().split('.')[1]
      this.formdata.applyCode = getNewUUID().replace(/\-/g, '')
      this.formdata.applyDateTime = dateFormatter(new Date())
      this.formdata.visitDateTime = dateFormatter(new Date())
    },
    // 获取随机数做id
    getRandom() {
      return Math.random().toString(36).substring(2)
    },
    getSource(row, column, val) {
      switch (val) {
        // 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
        case 0:
          return '未知'
        case 1:
          return '门诊'
        case 2:
          return '住院'
        case 3:
          return '体检'
        case 4:
          return '绿检'
        case 5:
          return '急诊'
        case 6:
          return '外院'
        default:
          return '未知'
      }
    },
    getParamsString(data) {
      const d = Object.keys(data).map(k => { return `${k}=${data[k]}` })
      return d.join('&')
    }
  }
}
</script>

<style lang="scss" scoped>
.his_container{
  padding: 0;
  margin: 0;
  h1{
    margin: 0;
  }
}
.header {
	height: 50px;
	line-height: 50px;
	border-bottom: 4px solid #009BDD;
	box-sizing: border-box;
	overflow: hidden;
}

.header h1 {
	float: left;
	background: #009BDD;
	padding: 0px 45px 6px 15px;
	font-size:22px;
	color:#fff;
	font-weight:100
}

.header h1 img {
	height: 35px;
	background-size: 100%;
	margin-top: 8px;
}

.header h5 {
	float: left;
	width: 50px;
	margin: -2px 0 0 -50px;
}

.header h5 img {
	height: 50px;
	background-size: 100%;
}

.header span {
	margin-left: 30px;
}

.header p {
	float: right;
	color: #ddd;
}

.header p span {
	margin: 0 18px;
	color: #0C6FE3;
	cursor: pointer;
}

.header p span em {
	display: inline-block;
	position: relative;
	top: 4px;
	margin-right: 5px;
}

.tree_box{
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}
.his_table{
  /deep/ .el-table__body-wrapper {
    max-height: calc(100vh - 250px);
    overflow-y: auto;
  }
}
</style>
